package com.atguigu.daijia.driver.interctpeor;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author 山顶洞人郑某
 * @className DriverInterceptor.java
 * @date 2024 09 05
 */
@Component
@Slf4j
public class DriverInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public DriverInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if (!Optional.ofNullable(token).isPresent()) {
            log.error("用户未登录");
            throw new GuiguException(ResultCodeEnum.NOT_LOGIN);
        }
        //刷新用户登录时间
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX+token;
        String userId = stringRedisTemplate.opsForValue().get(key);
        if (!Optional.ofNullable(userId).isPresent()) {
            throw new GuiguException(ResultCodeEnum.NOT_LOGIN);
        }
        stringRedisTemplate.opsForValue().set(key,userId,RedisConstant.USER_LOGIN_REFRESH_KEY_TIMEOUT, TimeUnit.MINUTES);
        AuthContextHolder.setUserId(Long.valueOf(userId));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      AuthContextHolder.removeUserId();
    }
}
